﻿using DbUpgradeOracle.General.更新数据库;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DbUpgradeOracle.General
{
    /// <summary>
    /// 更新
    /// </summary>
    public class Upgrade
    {
        #region 更新脚本链表
        /// <summary>
        /// 更新脚本链表
        /// </summary>
        private List<UpGradeDbBase> _upDbs = new List<UpGradeDbBase>();

        private object _lock_upDbs = new object();
        #endregion

        #region 实例
        private static Upgrade _instance;
        /// <summary>
        /// 实例
        /// </summary>
        public static Upgrade Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new Upgrade();
                }
                return _instance;
            }
        }
        #endregion

        private Upgrade()
        {
            lock (_lock_upDbs)
            {
                _upDbs.Add(new UpGradeDb1());
                _upDbs.Add(new UpGradeDb2());
                _upDbs.Add(new UpGradeDb3());
            }
        }

        #region 更新数据库版本
        /// <summary>
        /// 更新数据库版本
        /// </summary>
        public void UpDb()
        {
            string sqltable = "SELECT COUNT(*) FROM sqlite_master where type='table' and name='SqliteVersion'";
            int tablecount = App.Dal.ExecScalar(sqltable).ToInt32Ex();
            if (tablecount <= 0)
            {
                sqltable = @"CREATE TABLE 'SqliteVersion' (
                                        'Id'  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                        'Version'  INTEGER
                                        );";
                App.Dal.ExecNoQuery(sqltable);
            }

            string sql = "select Version from SqliteVersion where Id = 1";
            int oVersion = App.Dal.ExecScalar(sql).ToInt32Ex();
            lock (_lock_upDbs)
            {
                List<UpGradeDbBase> upbs = _upDbs.OrderBy(t => t.Version).ToList();
                for (int i = 0; i < upbs.Count; i++)
                {
                    if (upbs[i].Version > oVersion)
                    {
                        upbs[i].UpGradeVersion();
                    }
                }
            }
        }
        #endregion
    }
}
